import Config from '@/Config';
import ProjectUtil from '@/utils/ProjectUtil';

class ServiceBase {
  static get(url: string, params: any, header?: any) {
    return this.request('GET', url, params || {}, header);
  }

  static post(url: string, body?: any, header?: any) {
    return this.request('POST', url, body || {}, header);
  }

  static put(url: string, body?: any, header?: any) {
    return this.request('PUT', url, body || {}, header);
  }

  static delete(url: string, body?: any, header?: any) {
    return this.request('DELETE', url, body || {}, header);
  }

  static request(
    method: 'GET' | 'POST' | 'PUT' | 'DELETE',
    url: string,
    body?: any,
    header?: any
  ): Promise<{ errmsg: string; data: any }> {
    const headerData: any = { ...header };
    const token = uni.getStorageSync('token');
    if (token) {
      headerData['token'] = token;
    }
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.fullUrl(url),
        method,
        data: body,
        header: headerData,
        success: (res) => {
          const { statusCode, data } = res;
          if (statusCode < 200 || statusCode >= 300) {
            const { errmsg } = data as any;
            ProjectUtil.showErrorToast(errmsg);
            reject(errmsg);
          } else {
            resolve(data as any);
          }
        },
        fail: (error) => {
          ProjectUtil.showErrorToast(
            error.errMsg || error.toString() || '未知错误'
          );
          reject(error);
        },
      });
    });
  }

  private static fullUrl(url: string) {
    return encodeURI(
      url.indexOf('http') === 0 ? url : `${Config.SERVER}${url}`
    );
  }
}

export default ServiceBase;
